﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Threading;

namespace StressServer_UI
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private static Mutex _InstanceMutex = null;
        protected override void OnStartup(StartupEventArgs e)
        {
            // check that there is only one instance of the control panel running...
            bool createdNew;
            _InstanceMutex = new Mutex(true, @"StressServer", out createdNew);
            if (!createdNew)
            {
                _InstanceMutex = null;
                MessageBox.Show("Only one StressServer instance allowed to run");
                Application.Current.Shutdown();
                return;
            }

            base.OnStartup(e);
        }
        protected override void OnExit(ExitEventArgs e)
        {
            if (_InstanceMutex != null)
                _InstanceMutex.ReleaseMutex();
            base.OnExit(e);
        }
        public bool DoHandle { get; set; }
        private void Application_DispatcherUnhandledException(object sender,
                               System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            this.DoHandle = true;
            if (this.DoHandle)
            {
                MessageBox.Show(e.Exception.Message, "Exception caught",
                                        MessageBoxButton.OK, MessageBoxImage.Error);
                e.Handled = true;
            }
            else
            {
                //If you do not set e.Handled to true, the application will close due to crash.
                MessageBox.Show("Application is going to close! ", "Uncaught Exception");
                e.Handled = false;
            }
        }
    }
}
